package com.example.mybatisplus.web.controller;

import com.example.mybatisplus.mapper.ReviewMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.service.ReviewService;
import com.example.mybatisplus.model.domain.Review;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *
 *  前端控制器
 *
 *
 * @author lxp
 * @since 2025-03-10
 * @version v1.0
 */
@Controller
@RequestMapping("/api/review")
public class ReviewController {

    private final Logger logger = LoggerFactory.getLogger( ReviewController.class );

    @Autowired
    private ReviewService reviewService;
    @Autowired
    private ReviewMapper reviewMapper;

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        Review  review =  reviewService.getById(id);
        return JsonResponse.success(review);
    }

    /**
    * 描述：根据Id删除
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        reviewService.removeById(id);
        return JsonResponse.success(null);
    }


    /**
    * 描述：根据Id 更新
    *
    */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateReview(Review  review) throws Exception {
        reviewService.updateById(review);
        return JsonResponse.success(null);
    }


    /**
    * 描述:创建Review
    *
    */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(Review  review) throws Exception {
        reviewService.save(review);
        return JsonResponse.success(null);
    }

    @GetMapping("/sentimentDistribution")
    public ResponseEntity<Map<String, Integer>> getSentimentDistribution() {
        List<Map<String, Object>> rawData = reviewMapper.getSentimentDistribution();
        Map<String, Integer> distribution = new HashMap<>();

        for (Map<String, Object> entry : rawData) {
            Integer prediction = (Integer) entry.get("prediction");
            Integer count = ((Number) entry.get("count")).intValue(); // 防止返回 Long 类型

            // 0 -> 负面，1 -> 正面
            String key = (prediction == 1) ? "正面" : "负面";
            distribution.put(key, count);
        }

        return ResponseEntity.ok(distribution);
    }
}

